import addCollection from '../business/member/addCollection';
import immutable from '../lib/immutable';
import { FAIL } from '../utils/fail';

const Collect = {
    create: function create(config = {}) {
        const actionDispatcher = config.actionDispatcher;
        const onCollect = config.onCollect;
        const actionTypes = config.actionTypes || [];
        return {
            urlData: config.urlData || {},
            handle: function handle(event, params = immutable.fromJS({})) {
                if (!event || !event.toJS || !params.toJS) return;
                if (actionTypes.indexOf(event.get('id')) > -1) {
                    const token = params.get('token');
                    if (token) {
                        const type = 1;
                        const set_id = event.get('set_id');
                        let fieldIdValue = '';
                        const listData = params.getIn(['listData']);
                        // 找列表数据里面的对应id值
                        listData && listData.map((value, key) => {
                            const field = listData.getIn([key, 'field']);
                            if (field === 'id') {
                                fieldIdValue = listData.getIn([key, 'value']);
                            }
                        });
                        actionDispatcher.execute(addCollection, {
                            type,
                            relation_id: fieldIdValue,
                            token,
                            set_id,
                        }, onCollect);
                    } else {
                        onCollect && onCollect(FAIL, { token: undefined });
                    }
                }
            },
        };
    },
};
export default Collect;
